//
//  GPSTrainingInfoModel.swift
//  DaRings
//
//  Created by HFY on 2022/12/9.
//

import UIKit
import MYModule

open class GPSTrainingInfoModel: NSObject {
    
    public var targetItem: GPSTrainingInfoItemModel
    
    public var items: [GPSTrainingInfoItemModel]
    
    public init(type: TrainingTypeContent, goal: Double? = nil) {
        
        var targetType = TrainingTypeContent.distance
        var types: [TrainingTypeContent] = [.time, .pace, .calorie, .heartRate]
        
        if type != .unkown {
            
            if let index = types.firstIndex(where: { $0 == type }) {
                let replaceType = types[index]
                types[index] = targetType
                targetType = replaceType
            }
         }
        
        targetItem = GPSTrainingInfoItemModel.item(of: targetType)
        
        var targetValue = goal
        if let goal = goal {
            
            switch type {
           
            case .distance:
                targetValue = Unit.sharedInstance.goalDistance(goal).distance/1000.0
            case .pace:
                targetValue = Unit.sharedInstance.goalMetricPace(goal)
            default:
                break
            }
            
        }
    
        targetItem.targetData = targetValue
        items = types.map({ GPSTrainingInfoItemModel.item(of: $0) })
  
        super.init()
        
    }

}

extension GPSTrainingInfoModel {
    
    public var subItems: [GPSTrainingInfoItemModel] {
        var all = [targetItem]
         all.append(contentsOf: items)
        return all
        
    }
    
   public func updateData(type: TrainingTypeContent, currentData: Double) {
        
       let model = subItems.filter { $0.contentType == type }.first
       
       let currentData = currentData
       switch type {
           
       case .distance:
           
           let tuple = Unit.sharedInstance.GPSDistanceOf(currentData, unit: (.km, .miles))
           let distance = ceil(tuple.distance * 100) / 100
           model?.currentData = distance
        
           break

       default:
           
           model?.currentData = currentData
           break
       }
       
       
        
    }
    
    public func updateSpeed(_ speed: Double) {
        
        let model = subItems.filter { $0.contentType == .pace }.first
        model?.currentData = speed
        
    }
    
    
    
    
    
    
    
}
